package com.software.loginregister.fragment.homecategoryfragment;
import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.software.loginregister.R;
import com.software.loginregister.activity.MapLocationActivity;
import com.software.loginregister.adapter.RegionalFoodAdapter;
import com.software.loginregister.entity.RegionalFood;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

public class RegionalFoodFragment extends Fragment {
    private static final int PERMISSION_REQUEST_CODE = 1001;
    private RecyclerView rvFoodList;
    private RegionalFoodAdapter regionalFoodAdapter;
    private List<RegionalFood> regionalFoodList;
    private TextView tvLocation;
    private LocationManager locationManager;
    private LocationListener locationListener;
    private static final int REQUEST_LOCATION = 1002;
    private ImageView ivMore;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_regional_food, container, false);

        initViews(view);
        initData();
        setupRecyclerView();
        setupLocation();
        setupClickListeners();

        return view;
    }

    private void initViews(View view) {
        rvFoodList = view.findViewById(R.id.rv_food_list);
        tvLocation = view.findViewById(R.id.tv_location);
        ivMore = view.findViewById(R.id.iv_more);
    }

    private void setupClickListeners() {
        ivMore.setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), MapLocationActivity.class);
            startActivityForResult(intent, REQUEST_LOCATION);
        });
    }

    private void initData() {
        regionalFoodList = new ArrayList<>();
        regionalFoodList.add(new RegionalFood("烧鸡", "石家庄烧鸡外皮酥脆，肉质鲜嫩多汁...", 3.9f, R.drawable.bg_weight_losses));
        regionalFoodList.add(new RegionalFood("包肉面包", "石家庄特色汉堡塔多，肉馅鲜嫩...", 4.6f, R.drawable.bg_health_food));
        regionalFoodList.add(new RegionalFood("烤包子", "石家庄烤包子外皮酥脆，内馅鲜嫩多汁...", 3.9f, R.drawable.bg_drinks));
        // 添加更多美食项
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_LOCATION && resultCode == Activity.RESULT_OK && data != null) {
            String location = data.getStringExtra("location");
            if (location != null) {
                tvLocation.setText("当前位置：" + location);
            }
        }
    }

    private void setupRecyclerView() {
        regionalFoodAdapter = new RegionalFoodAdapter(regionalFoodList);
        rvFoodList.setLayoutManager(new LinearLayoutManager(getContext()));
        rvFoodList.setAdapter(regionalFoodAdapter);
    }

    private void setupLocation() {
        locationManager = (LocationManager) requireContext().getSystemService(getContext().LOCATION_SERVICE);

        locationListener = new LocationListener() {
            @Override
            public void onLocationChanged(@NonNull Location location) {
                updateLocationText(location);
                locationManager.removeUpdates(locationListener);
            }

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {}

            @Override
            public void onProviderEnabled(@NonNull String provider) {}

            @Override
            public void onProviderDisabled(@NonNull String provider) {
                Toast.makeText(getContext(), "请开启定位服务", Toast.LENGTH_SHORT).show();
            }
        };

        if (ContextCompat.checkSelfPermission(requireContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(requireActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSION_REQUEST_CODE);
        } else {
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 10, locationListener);
        }
    }

    private void updateLocationText(Location location) {
        Geocoder geocoder = new Geocoder(getContext(), Locale.getDefault());
        try {
            List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
            if (addresses != null && !addresses.isEmpty()) {
                Address address = addresses.get(0);
                String locationStr = address.getLocality() + "·" + address.getSubLocality();
                tvLocation.setText("当前位置：" + locationStr);
            }
        } catch (IOException e) {
            e.printStackTrace();
            tvLocation.setText("获取地址失败");
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                setupLocation();
            } else {
                Toast.makeText(getContext(), "需要定位权限才能使用此功能", Toast.LENGTH_SHORT).show();
            }
        }
    }
}